/*分析TCP/IP协议接收数据包类
Created on 2020年05月10日
@author: zxyong 13738196011
 */

package com.zxy.business;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

import com.zxy.adminlog.UsAdmin_Log;
import com.zxy.common.Com_Fun;
import com.zxy.common.Com_Para;
import com.zxy.common.DbConfigSelf;
import com.zxy.common.ParamName_InterFace;

public class Analyse_Data
{
	public String	TemChildNode	= "";

	// 作为服务端接收到数据包 iServ 是否作为服务端接收到数据
	public String SubAnalyseRecBytes(int iLength,char[] Bytes,Socket mServSocket,Boolean iServ,String strIP) throws Exception
	{
		for(Enumeration<String> sm = Com_Para.htChildNode.keys();sm.hasMoreElements();)
		{
			TemChildNode = sm.nextElement();
			if(Com_Para.htChildNode.get(TemChildNode) != null && Com_Para.htChildNode.get(TemChildNode).toString().equals("servSocket" + mServSocket.getInetAddress().getHostAddress()))
			{
				break;
			}
			else
			{
				TemChildNode = "";
			}
		}

		StringBuilder strResult = new StringBuilder();
		for(int i = 0;i < iLength;i++)
		{
			strResult.append(Bytes[i]);
		}

		// 作为服务端接收数据拦截器
		if(!Com_Para.ServerREFLECT_IN_CLASS.equals(""))
		{
			String temContinue = "";
			try
			{
				Class<?> objC = Class.forName(Com_Para.ServerREFLECT_IN_CLASS);
				ParamName_InterFace pni = (ParamName_InterFace)objC.newInstance();
				for(Field field: pni.getClass().getDeclaredFields())
				{
					field.setAccessible(true);
					if(field.getName().equals("strResult"))
						field.set(pni,strResult);
					else if(field.getName().equals("strIP"))
						field.set(pni,strIP);
				}
				pni.init_start();
				for(Field field: pni.getClass().getDeclaredFields())
				{
					if(field.getName().equals("strSend"))
					{
						Object fieldGetName = Com_Fun.getFieldValueByName(field.getName(),pni);
						if(!fieldGetName.toString().equals(""))
						{
							// String strTemSend = fieldGetName.toString();
						}
					}
					else if(field.getName().equals("strResult"))
					{
						Object fieldGetName = Com_Fun.getFieldValueByName(field.getName(),pni);
						if(!fieldGetName.toString().equals(""))
						{
							// String strTemResult = fieldGetName.toString();
						}
					}
					else if(field.getName().equals("strContinue"))
					{
						Object fieldGetName = Com_Fun.getFieldValueByName(field.getName(),pni);
						if(!fieldGetName.toString().equals(""))
						{
							temContinue = fieldGetName.toString();
						}
					}
				}
				if(temContinue.equals("0"))
					return "";
			}
			catch(Exception ee)
			{
				System.err.println(Com_Para.ServerREFLECT_IN_CLASS + "作为服务端接收数据拦截器获取失败!" + strResult.toString() + "***" + ee.getMessage());
				com.zxy.adminlog.UsAdmin_Log uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,new StringBuilder("解析协议包失败，作为服务端接收数据拦截器获取失败[GetPackageInfo]\r\n" + strResult.toString() + " " + ee.getMessage()));
				try
				{
					uL.WriteLog();
				}
				catch(IOException e1)
				{
				}
			}
		}

		// 接收数据包
		for(String strAryT: strResult.toString().split("\\\\r\\\\n"))
		{
			strAryT = strAryT.replaceAll("\r","").replaceAll("\n","");
			Hashtable<String,String> ht = null;
			ArrayList<String> al = new ArrayList<String>();

			if(DbConfigSelf.UserDebug.indexOf("|10|") != -1)
			{
				// 数据日志输出
				StringBuilder sb = new StringBuilder();
				sb.append("接收到客户端数据:" + strAryT);
				UsAdmin_Log uL = new UsAdmin_Log(Com_Para.ApplicationPath,sb);
				uL.WriteLogSub("RecDataServer");
			}
			// 协议含包头和包尾
			if(strAryT.length() > 3 && strAryT.indexOf("@##") == 0 && strAryT.indexOf("##@") == strAryT.length() - 3)
			{
				// 获取子设备Child_Node
				if(strAryT.indexOf("@##ST=01") != -1)
				{
					ht = GetPackageInfo(strAryT);
					Com_Para.htChildNode.put(ht.get("CHILD_NODE").toString(),"servSocket" + mServSocket.getInetAddress().getHostAddress());
				}
				// 获取业务数据
				else if(strAryT.indexOf("@##ST=03") != -1)
				{
					ht = GetPackageInfo(strAryT);
					if(TemChildNode != "")
						Com_Para.htChildInfo.put(TemChildNode,ht.get("VALUE").toString());
					Com_Para.htTempChildInfo.put(ht.get("CHILD_NODE").toString(),"");
				}
				// 直接获取业务数据
				else if(strAryT.indexOf("@##ST=04") != -1)
				{
					ht = GetPackageInfo(strAryT);
					Query_Data gd = new Query_Data();
					for(int in = 1;in < 101;in++)
					{
						String strVS = "";
						if(ht.get("param_value" + String.valueOf(in)) != null)
						{
							strVS = (String)ht.get("param_value" + String.valueOf(in));
						}
						else break;
						al.add(in - 1,strVS);
					}
					String sub_code = ht.get("sub_code") == null ? "" : (String)ht.get("sub_code");
					String sub_usercode = ht.get("sub_usercode") == null ? "" : (String)ht.get("sub_usercode");
					String delay_data = ht.get("delay_data") == null ? "" : (String)ht.get("delay_data");
					String delay_code = ht.get("delay_code") == null ? "" : (String)ht.get("delay_code");
					String param_name = ht.get("param_name") == null ? "" : (String)ht.get("param_name");
					StringBuilder sbd = gd.GetDataList(sub_code,sub_usercode,param_name,al,new StringBuilder(strAryT),delay_data,delay_code,strIP);
					Send03(sbd.toString(),mServSocket);
				}
			}
			// 协议含包头，无包尾
			else if(strAryT.length() > 3 && strAryT.indexOf("@##") == 0 && strAryT.indexOf("##@") == -1)
			{
				ht = GetPackageInfo(strAryT);
				if(TemChildNode != "")
					Com_Para.htTempChildInfo.put(TemChildNode,ht.get("VALUE").toString());
			}
			// 协议无包头,含包尾
			else if(strAryT.indexOf("@##") == -1 && strAryT.indexOf("##@") != -1)
			{
				// 获取子设备Child_Node
				if(TemChildNode != "")
					Com_Para.htChildInfo.put(TemChildNode,Com_Para.htTempChildInfo.get(TemChildNode) + strAryT.replaceAll("##@",""));
				Com_Para.htTempChildInfo.put(TemChildNode,"");
				// 直接获取业务数据
				if(strAryT.indexOf("@##ST=04") != -1)
				{
					ht = GetPackageInfo(strAryT);
					Query_Data gd = new Query_Data();
					for(int in = 1;in < 101;in++)
					{
						String strVS = "";
						if(ht.get("param_value" + String.valueOf(in)) != null)
						{
							strVS = (String)ht.get("param_value" + String.valueOf(in));
						}
						else break;
						al.add(in - 1,strVS);
					}
					String sub_code = ht.get("sub_code") == null ? "" : (String)ht.get("sub_code");
					String sub_usercode = ht.get("sub_usercode") == null ? "" : (String)ht.get("sub_usercode");
					String delay_data = ht.get("delay_data") == null ? "" : (String)ht.get("delay_data");
					String delay_code = ht.get("delay_code") == null ? "" : (String)ht.get("delay_code");
					String param_name = ht.get("param_name") == null ? "" : (String)ht.get("param_name");
					StringBuilder sbd = gd.GetDataList(sub_code,sub_usercode,param_name,al,new StringBuilder(strAryT),delay_data,delay_code,strIP);
					Send03(sbd.toString(),mServSocket);
				}
			}
			// 协议包中间
			else if(!strAryT.equals("") && strAryT.indexOf("@##") == -1 && strAryT.indexOf("##@") == -1)
			{
				if(TemChildNode != "")
					Com_Para.htTempChildInfo.put(TemChildNode,Com_Para.htTempChildInfo.get(TemChildNode) + strAryT.replaceAll("##@",""));
			}
		}
		return "";
	}

	// 作为客户端接收到服务端请求数据包
	public void SubClientRecBytes(int iLength,char[] Bytes,Socket mServSocket,Boolean iServ,String strIP) throws Exception
	{
		StringBuilder strResult = new StringBuilder();
		for(int i = 0;i < iLength;i++)
		{
			strResult.append(Bytes[i]);
		}
		// 接收数据包
		for(String strAryT: strResult.toString().split("\\\\r\\\\n"))
		{
			strAryT = strAryT.replaceAll("\r","").replaceAll("\n","");
			if(DbConfigSelf.UserDebug.indexOf("|10|") != -1)
			{
				// 数据日志输出
				StringBuilder sb = new StringBuilder();
				sb.append("接收到服务端数据:" + strAryT + Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss:SSS"));
				UsAdmin_Log uL = new UsAdmin_Log(Com_Para.ApplicationPath,sb);
				uL.WriteLogSub("RecDataClient");
			}
			Hashtable<String,String> htParam = null;
			ArrayList<String> al = new ArrayList<String>();
			if(strAryT.indexOf("@##") == 0 && strAryT.indexOf("##@") == strAryT.length() - 3)
			{
				// 获取业务数据
				if(strAryT.indexOf("@##ST=02") != -1)
				{
					htParam = GetPackageInfo(strAryT);
					Query_Data gd = new Query_Data();
					for(int in = 1;in < 101;in++)
					{
						String strVS = "";
						if(htParam.get("param_value" + String.valueOf(in)) != null)
						{
							strVS = (String)htParam.get("param_value" + String.valueOf(in));
						}
						else break;
						al.add(in - 1,strVS);
					}
					String sub_code = htParam.get("sub_code") == null ? "" : (String)htParam.get("sub_code");
					String sub_usercode = htParam.get("sub_usercode") == null ? "" : (String)htParam.get("sub_usercode");
					String delay_data = htParam.get("delay_data") == null ? "" : (String)htParam.get("delay_data");
					String delay_code = htParam.get("delay_code") == null ? "" : (String)htParam.get("delay_code");
					String param_name = htParam.get("param_name") == null ? "" : (String)htParam.get("param_name");
					StringBuilder sbd = gd.GetDataList(sub_code,sub_usercode,param_name,al,new StringBuilder(strAryT),delay_data,delay_code,strIP);
					Send03(sbd.toString(),mServSocket);
				}
			}
			// 协议无包头,含包尾
			else if(strAryT.indexOf("@##") == -1 && strAryT.indexOf("##@") != -1)
			{
				// 获取业务数据
				if(strAryT.indexOf("@##ST=02") != -1)
				{
					htParam = GetPackageInfo(strAryT.replaceAll("\r","").replaceAll("\n",""));
					Query_Data gd = new Query_Data();
					for(int in = 1;in < 101;in++)
					{
						String strVS = "";
						if(htParam.get("param_value" + String.valueOf(in)) != null)
						{
							strVS = (String)htParam.get("param_value" + String.valueOf(in));
						}
						else break;
						al.add(in - 1,strVS);
					}
					String sub_code = htParam.get("sub_code") == null ? "" : (String)htParam.get("sub_code");
					String sub_usercode = htParam.get("sub_usercode") == null ? "" : (String)htParam.get("sub_usercode");
					String delay_data = htParam.get("delay_data") == null ? "" : (String)htParam.get("delay_data");
					String delay_code = htParam.get("delay_code") == null ? "" : (String)htParam.get("delay_code");
					String param_name = htParam.get("param_name") == null ? "" : (String)htParam.get("param_name");
					StringBuilder sbd = gd.GetDataList(sub_code,sub_usercode,param_name,al,new StringBuilder(strAryT),delay_data,delay_code,strIP);
					Send03(sbd.toString(),mServSocket);
				}
			}
			else if(strAryT.indexOf("@##") == -1 && strAryT.indexOf("##@") == -1)
			{
			}
		}
	}

	public Hashtable<String,String> GetPackageInfo(String strInfo)
	{
		Hashtable<String,String> ht = new Hashtable<String,String>();
		for(String strs: strInfo.replace("@##","").replace("##@","").split("&"))
		{
			ht.put(strs.split("=")[0],strs.split("=")[1]);
		}
		return ht;
	}

	// 发送TCP/IP数据 字符串形式发送
	public void SendSocket(StringBuilder strInput,Socket sc) throws Exception
	{
		if(DbConfigSelf.UserDebug.indexOf("|10|") != -1)
		{
			// 数据日志输出
			StringBuilder sb = new StringBuilder();
			sb.append("通用发送数据包:" + strInput + Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss:SSS"));
			UsAdmin_Log uL = new UsAdmin_Log(Com_Para.ApplicationPath,sb);
			uL.WriteLogSub("SendData");
		}
		sc.setSendBufferSize(1024 * 20);
		BufferedOutputStream bos = null;
		try
		{
			bos = new BufferedOutputStream(sc.getOutputStream());
			bos.write(strInput.toString().getBytes(Com_Para.U_CODE));
			bos.write("\r\n".getBytes(Com_Para.U_CODE));
			bos.flush();
			Thread.sleep(500);
		}
		catch(Exception e)
		{
		}
	}

	// 发送TCP/IP数据 字节形式发送
	public void SendSocket(char[] bytes,Socket sc) throws Exception
	{
		sc.setSendBufferSize(1024);
		PrintWriter writer = null;
		OutputStreamWriter owr = null;
		try
		{
			owr = new OutputStreamWriter(sc.getOutputStream(),Com_Para.U_CODE);
			writer = new PrintWriter(owr);
			writer.write(bytes,0,bytes.length);
			writer.flush();
			Thread.sleep(500);
		}
		catch(Exception e)
		{
		}
		finally
		{
			writer.close();
		}
	}

	public void Send01(Socket sc) throws Exception
	{
		StringBuilder strInput = new StringBuilder();
		strInput.append("@##ST=01&DATATIME=" + Com_Fun.DateTimeStr("yyyyMMddHHmmss") + "&CHILD_NODE=" + Com_Para.Child_Code + "##@\r\n");
		SendSocket(strInput,sc);
	}

	public void Send02(StringBuilder strUrl,Socket sc) throws Exception
	{
		StringBuilder strInput = new StringBuilder();
		strInput.append("@##ST=02&");
		if(strUrl.toString().indexOf("DATATIME=") != -1)
		{
			strInput.delete(0,strInput.length());
			strInput.append(strUrl.toString());
		}
		else strInput.append("DATATIME=" + Com_Fun.DateTimeStr("yyyyMMddHHmmss") + "&" + strUrl + "##@\r\n");
		SendSocket(strInput,sc);
	}

	public void Send03(String strInfo,Socket sc) throws Exception
	{
		StringBuilder strInput = new StringBuilder();
		strInput.append("@##ST=03&CHILD_NODE=" + Com_Para.Child_Code + "&VALUE=" + strInfo + "##@\r\n");
		SendSocket(strInput,sc);
	}

	public void SendReg(Socket sc) throws Exception
	{
		StringBuilder strInput = new StringBuilder();
		strInput.append("@##ST=50&CHILD_NODE=" + Com_Para.Child_Code + "&DEVICE_NAME=" + Com_Para.S_DESC + "##@\r\n");
		SendSocket(strInput,sc);
	}
}